from flask import Flask, render_template, request,jsonify,escape
import panduan


app = Flask(__name__)

def log_request(req:"flask request",res:str):
    with open("vsearch.log","a") as log:
        print(req.form,req.host_url,req.remote_addr,res,file=log,sep="|")

@app.route('/')
def hello() -> str:
    return "hello wrold"


@app.route('/search',methods = ['POST'])
def search():
    phrase = request.form.get("phrase")
    letters = request.form.get("letters")
    results = phrase + letters
    log_request(request,results)
    title = "Here are your results"
    return render_template("results.html",the_title=title,the_phrase=phrase,the_letters=letters,the_results=results)



@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html',the_title ="welcome to searchletters on the web!")

@app.route('/results',methods = ['GET'])
def results_page() -> 'html':
    return render_template('results.html',the_title ="welcome to searchletters on the web!")

@app.route("/viewlog")
def view_log():
    contents=[]
    with open("vsearch.log","r") as log:
        for line in log:
            contents.append([])
            for item in line.split("|"):
                contents[-1].append(escape(item))

    titles= ["Formdata","Host_url","Remote_addr","results"]
    return render_template("view.html",the_data=contents,the_titles=titles)

if __name__ == '__main__':
    app.run(debug = True)